package com.cj.aspect;

import com.cj.Service.LogService;
import com.cj.annotation.ControllerLog;
import com.cj.pojo.LogPojo;
import com.cj.util.IPUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class AspectLog {

    @Autowired
    LogService logService;

    // 定义切入点

    @Around(value = "@annotation(controllerLog)")
    public  Object LogAround(ProceedingJoinPoint joinPoint , ControllerLog controllerLog) throws Throwable {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();
        // 获取ip 地址
        String  ipaddress = IPUtils.getIpAddr();
        // 获取注解上的方法
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        String method = ms.getMethod().getName();
        // 获取参数
        String params = Arrays.toString(joinPoint.getArgs());
        // 当前时间
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        // 执行目标方法
        Object result = joinPoint.proceed();

        // 记录日志
        LogPojo logPojo = new LogPojo();
        logPojo.setUsername(username);
        logPojo.setIpaddress(ipaddress);
        logPojo.setMethod(method);
        logPojo.setParams(params);
        logPojo.setCreatetime(dateFormat.format(date));
        logService.addLog(logPojo);

        return  result;
    }

}
